<template>
  <div class="teaching-content">
    <!-- 页面头部 -->
    <div class="page-header">
      <button class="back-btn" @click="goBack">
        ← 返回
      </button>
      <h1>📝 教学内容</h1>
    </div>

    <!-- 标签页 -->
    <div class="tabs">
      <button
        :class="['tab-btn', { active: activeTab === 'courseware' }]"
        @click="activeTab = 'courseware'"
      >
        📄 课件管理
      </button>
      <button
        :class="['tab-btn', { active: activeTab === 'picturebook' }]"
        @click="activeTab = 'picturebook'"
      >
        📚 绘本管理
      </button>
      <button
        :class="['tab-btn', { active: activeTab === 'audio' }]"
        @click="activeTab = 'audio'"
      >
        🎵 音频管理
      </button>
      <button
        :class="['tab-btn', { active: activeTab === 'recommend' }]"
        @click="activeTab = 'recommend'"
      >
        ⭐ 每日推荐
      </button>
    </div>

    <!-- 课件管理 -->
    <div v-if="activeTab === 'courseware'" class="tab-content">
      <div class="section-header">
        <h2>课件上传下载</h2>
        <div class="header-actions">
          <button class="btn-primary" @click="showUploadDialog = true">
            📤 上传课件
          </button>
          <button class="btn-secondary" @click="showBatchPanel = !showBatchPanel">
            📋 批量操作
          </button>
        </div>
      </div>

      <!-- 批量操作面板 -->
      <div v-if="showBatchPanel" class="batch-panel">
        <h3>批量操作面板</h3>
        <div class="batch-controls">
          <div class="filter-group">
            <label>按班级筛选：</label>
            <select v-model="batchSelectedClass" class="class-select">
              <option value="">全部班级</option>
              <option v-for="classItem in classes" :key="classItem.id" :value="classItem.id">
                {{ classItem.name }}
              </option>
            </select>
          </div>
          <div class="checkbox-group">
            <label>
              <input type="checkbox" v-model="selectAll" @change="toggleSelectAll" />
              全选课件库
            </label>
          </div>
          <button class="btn-primary" @click="batchPush">
            🚀 一键推送
          </button>
        </div>
      </div>

      <!-- 课件卡片列表 -->
      <div class="content-list" v-if="coursewares && coursewares.length > 0">
        <div class="content-card" v-for="courseware in coursewares" :key="courseware.id || courseware.fileName">
          <div class="content-header">
            <h3>{{ courseware.displayName || courseware.name || courseware.originalName || courseware.fileName }}</h3>
            <span class="content-meta">
              大小: {{ formatFileSize(courseware.size) }} | 上传时间: {{ formatDate(courseware.uploadTime) }}
              <span class="review-status" :class="getReviewStatusClass(courseware.reviewStatus)">
                {{ getReviewStatusText(courseware.reviewStatus) }}
              </span>
            </span>
          </div>
          <div class="content-actions">
            <label class="checkbox-label">
              <input type="checkbox" v-model="courseware.selected" />
              选择
            </label>
            <button class="btn-secondary" @click="downloadCourseware(courseware)">
              ⬇️ 下载
            </button>
            <button class="btn-secondary" @click="previewCourseware(courseware)">
              👁️ 预览
            </button>
            <button 
              class="btn-danger" 
              @click="deleteCourseware(courseware)"
              :disabled="(courseware.reviewStatus !== 0 && courseware.reviewStatus !== null && courseware.reviewStatus !== undefined)"
              :title="(courseware.reviewStatus === 0 || courseware.reviewStatus === null || courseware.reviewStatus === undefined) ? '删除' : '已审核的文件不能删除'">
              🗑️ 删除
            </button>
          </div>
        </div>
      </div>
      <div v-if="(!coursewares || coursewares.length === 0) && !loadingCoursewares" class="empty-state">
        <p>暂无课件，请上传课件</p>
      </div>
      <div v-if="loadingCoursewares" class="loading-state">
        <p>加载中...</p>
      </div>
    </div>

    <!-- 绘本管理 -->
    <div v-if="activeTab === 'picturebook'" class="tab-content">
      <div class="section-header">
        <h2>绘本管理</h2>
        <div class="header-actions">
          <button class="btn-primary" @click="showUploadDialog = true">
            📤 上传绘本
          </button>
          <button class="btn-secondary" @click="showBatchPanel = !showBatchPanel">
            📋 批量操作
          </button>
        </div>
      </div>

      <!-- 批量操作面板 -->
      <div v-if="showBatchPanel" class="batch-panel">
        <h3>批量操作面板</h3>
        <div class="batch-controls">
          <div class="filter-group">
            <label>按班级筛选：</label>
            <select v-model="batchSelectedClass" class="class-select">
              <option value="">全部班级</option>
              <option v-for="classItem in classes" :key="classItem.id" :value="classItem.id">
                {{ classItem.name }}
              </option>
            </select>
          </div>
          <div class="checkbox-group">
            <label>
              <input type="checkbox" v-model="selectAll" @change="toggleSelectAll" />
              全选绘本库
            </label>
          </div>
          <button class="btn-primary" @click="batchPush">
            🚀 一键推送
          </button>
        </div>
      </div>

      <!-- 绘本卡片列表 -->
      <div class="content-list" v-if="picturebooks && picturebooks.length > 0">
        <div class="content-card" v-for="book in picturebooks" :key="book.id || book.fileName">
          <div class="content-header">
            <h3>{{ book.displayName || book.name || book.originalName || book.fileName }}</h3>
            <span class="content-meta">
              大小: {{ formatFileSize(book.size) }} | 上传时间: {{ formatDate(book.uploadTime) }}
              <span class="review-status" :class="getReviewStatusClass(book.reviewStatus)">
                {{ getReviewStatusText(book.reviewStatus) }}
              </span>
            </span>
          </div>
          <div class="content-actions">
            <label class="checkbox-label">
              <input type="checkbox" v-model="book.selected" />
              选择
            </label>
            <button class="btn-secondary" @click="downloadPicturebook(book)">
              ⬇️ 下载
            </button>
            <button class="btn-secondary" @click="previewPicturebook(book)">
              👁️ 预览
            </button>
            <button 
              class="btn-danger" 
              @click="deletePicturebook(book)"
              :disabled="(book.reviewStatus !== 0 && book.reviewStatus !== null && book.reviewStatus !== undefined)"
              :title="(book.reviewStatus === 0 || book.reviewStatus === null || book.reviewStatus === undefined) ? '删除' : '已审核的文件不能删除'">
              🗑️ 删除
            </button>
          </div>
        </div>
      </div>
      <div v-if="(!picturebooks || picturebooks.length === 0) && !loadingPicturebooks" class="empty-state">
        <p>暂无绘本，请上传绘本</p>
      </div>
      <div v-if="loadingPicturebooks" class="loading-state">
        <p>加载中...</p>
      </div>
    </div>

    <!-- 音频管理 -->
    <div v-if="activeTab === 'audio'" class="tab-content">
      <div class="section-header">
        <h2>音频上传下载</h2>
        <div class="header-actions">
          <button class="btn-primary" @click="showUploadDialog = true">
            📤 上传音频
          </button>
          <button class="btn-secondary" @click="showBatchPanel = !showBatchPanel">
            📋 批量操作
          </button>
        </div>
      </div>

      <!-- 批量操作面板 -->
      <div v-if="showBatchPanel" class="batch-panel">
        <h3>批量操作面板</h3>
        <div class="batch-controls">
          <div class="filter-group">
            <label>按班级筛选：</label>
            <select v-model="batchSelectedClass" class="class-select">
              <option value="">全部班级</option>
              <option v-for="classItem in classes" :key="classItem.id" :value="classItem.id">
                {{ classItem.name }}
              </option>
            </select>
          </div>
          <div class="checkbox-group">
            <label>
              <input type="checkbox" v-model="selectAll" @change="toggleSelectAll" />
              全选音频库
            </label>
          </div>
          <button class="btn-primary" @click="batchPush">
            🚀 一键推送
          </button>
        </div>
      </div>

      <!-- 音频卡片列表 -->
      <div class="content-list" v-if="audios && audios.length > 0">
        <div class="content-card" v-for="audio in audios" :key="audio.id || audio.fileName">
          <div class="content-header">
            <h3>{{ audio.displayName || audio.name || audio.originalName || audio.fileName }}</h3>
            <span class="content-meta">
              大小: {{ formatFileSize(audio.size) }} | 上传时间: {{ formatDate(audio.uploadTime) }}
              <span class="review-status" :class="getReviewStatusClass(audio.reviewStatus)">
                {{ getReviewStatusText(audio.reviewStatus) }}
              </span>
            </span>
          </div>
          <div class="content-actions">
            <label class="checkbox-label">
              <input type="checkbox" v-model="audio.selected" />
              选择
            </label>
            <button class="btn-secondary" @click="downloadAudio(audio)">
              ⬇️ 下载
            </button>
            <button class="btn-secondary" @click="previewAudio(audio)">
              👁️ 预览
            </button>
            <button 
              class="btn-danger" 
              @click="deleteAudio(audio)"
              :disabled="(audio.reviewStatus !== 0 && audio.reviewStatus !== null && audio.reviewStatus !== undefined)"
              :title="(audio.reviewStatus === 0 || audio.reviewStatus === null || audio.reviewStatus === undefined) ? '删除' : '已审核的文件不能删除'">
              🗑️ 删除
            </button>
          </div>
        </div>
      </div>
      <div v-if="(!audios || audios.length === 0) && !loadingAudios" class="empty-state">
        <p>暂无音频，请上传音频</p>
      </div>
      <div v-if="loadingAudios" class="loading-state">
        <p>加载中...</p>
      </div>
    </div>

    <!-- 每日推荐 -->
    <div v-if="activeTab === 'recommend'" class="tab-content recommend-content">
      <div class="section-header">
        <h2>每日课件或英语绘本推荐</h2>
        <div class="header-actions">
          <button class="btn-primary" @click="saveRecommendation">
            💾 保存推荐
          </button>
        </div>
      </div>

      <div class="recommend-layout">
        <!-- 左侧：班级和学生列表 -->
        <div class="recommend-sidebar">
          <h3>选择班级和学生</h3>
          
          <!-- 班级选择 -->
          <div class="class-selector">
            <label class="selector-label">
              <span>班级列表</span>
              <label class="select-all-label">
                <input
                  type="checkbox"
                  :checked="allClassesSelected"
                  :indeterminate="someClassesSelected"
                  @change="toggleAllClasses"
                  @click.stop
                />
                <span>全选</span>
              </label>
            </label>
            <div class="class-list">
              <div
                v-for="classItem in classes"
                :key="classItem.id"
                :class="['class-item', { active: selectedClasses.includes(classItem.id) }]"
                @click="toggleClass(classItem.id)"
              >
                <label class="class-checkbox-label">
                  <input
                    type="checkbox"
                    :checked="selectedClasses.includes(classItem.id)"
                    @change="toggleClass(classItem.id)"
                    @click.stop
                  />
                  <span class="class-name">{{ classItem.name }}</span>
                </label>
              </div>
            </div>
          </div>

          <!-- 学生列表 -->
          <div class="student-selector">
            <label class="selector-label">
              <span>学生列表</span>
              <label class="select-all-label" v-if="filteredStudents.length > 0">
                <input
                  type="checkbox"
                  :checked="allStudentsSelected"
                  :indeterminate="someStudentsSelected"
                  @change="toggleAllStudents"
                  @click.stop
                />
                <span>全选</span>
              </label>
            </label>
            <div class="student-list">
              <div
                v-for="student in filteredStudents"
                :key="student.id"
                :class="['student-item', { active: selectedStudents.includes(student.id) }]"
                @click="toggleStudent(student.id)"
              >
                <label class="student-checkbox-label">
                  <input
                    type="checkbox"
                    :checked="selectedStudents.includes(student.id)"
                    @change="toggleStudent(student.id)"
                    @click.stop
                  />
                  <div class="student-info">
                    <span class="student-name">{{ student.nickname || student.username }}</span>
                    <span class="student-class" v-if="student.className">{{ student.className }}</span>
                  </div>
                </label>
              </div>
            </div>
            <div v-if="filteredStudents.length === 0" class="empty-hint">
              <p>请先选择班级</p>
            </div>
          </div>
        </div>

        <!-- 中间：推荐内容编辑区 -->
        <div class="recommend-editor">
          <div class="editor-header">
            <h3 v-if="selectedStudents.length > 0">
              为 {{ selectedStudents.length }} 位学生撰写推荐内容
            </h3>
            <h3 v-else>
              请从左侧选择学生
            </h3>
          </div>
          <div class="editor-toolbar">
            <button class="toolbar-btn" @click="insertVoice">🎤 插入语音</button>
            <button class="toolbar-btn" @click="insertLink">🔗 附加课件链接</button>
            <button 
              class="toolbar-btn" 
              :class="{ active: activeFormats.bold }"
              @click="formatText('bold')"
            >B</button>
            <button 
              class="toolbar-btn" 
              :class="{ active: activeFormats.italic }"
              @click="formatText('italic')"
            >I</button>
            <button 
              class="toolbar-btn" 
              :class="{ active: activeFormats.underline }"
              @click="formatText('underline')"
            >U</button>
          </div>
          
          <!-- 录音对话框 -->
          <AudioRecorder 
            :show="showAudioRecorder" 
            @close="showAudioRecorder = false"
            @insert="handleInsertAudio"
          />
          
          <!-- 课件上传对话框 -->
          <CoursewareUploadDialog 
            :show="showCoursewareUpload" 
            @close="showCoursewareUpload = false"
            @insert="handleInsertCourseware"
          />
          
          <!-- 提示对话框 -->
          <div v-if="showTipDialog" class="modal-overlay tip-dialog-overlay" @click.self="showTipDialog = false">
            <div class="modal-content tip-dialog" @click.stop>
              <div class="tip-dialog-header">
                <div class="tip-icon" :class="tipDialogConfig.type">
                  <span>{{ tipDialogConfig.icon }}</span>
                </div>
                <h3 class="tip-title">{{ tipDialogConfig.title }}</h3>
                <button class="tip-close-btn" @click="showTipDialog = false">×</button>
              </div>
              <div class="tip-dialog-body">
                <p class="tip-message">{{ tipDialogConfig.message }}</p>
              </div>
              <div class="tip-dialog-footer">
                <button class="btn-primary tip-confirm-btn" @click="showTipDialog = false">我知道了</button>
              </div>
            </div>
          </div>
          
          <!-- 预览对话框 -->
          <div v-if="showPreviewModal" class="preview-modal-overlay" @click.self="showPreviewModal = false">
            <div class="preview-modal" @click.stop>
              <div class="preview-header">
                <h3>预览推荐内容</h3>
                <button class="close-btn" @click="showPreviewModal = false">×</button>
              </div>
              <div class="preview-content-wrapper">
                <div class="preview-content" v-html="previewContent"></div>
              </div>
              <div class="preview-footer">
                <button class="btn-secondary" @click="showPreviewModal = false">关闭</button>
              </div>
            </div>
          </div>
          
          <div
            class="rich-editor"
            contenteditable="true"
            ref="richEditor"
            @input="updateRecommendationContent"
            @compositionstart="onCompositionStart"
            @compositionend="onCompositionEnd"
            @click="handleEditorClickAndCheckFormat"
            @keyup="checkFormatState"
            placeholder="在此输入推荐内容..."
          ></div>
          <div class="editor-footer">
            <button class="btn-secondary" @click="previewRecommendation">👁️ 预览</button>
            <button class="btn-primary" @click="sendRecommendation">📤 发送推荐</button>
          </div>
        </div>

        <!-- 右侧：课件、绘本、音频列表 -->
        <div class="recommend-resources">
          <h3>推荐资源</h3>
          <div class="resource-type-selector">
            <button
              :class="['type-btn', { active: recommendType === 'courseware' }]"
              @click="recommendType = 'courseware'"
            >
              📄 课件
            </button>
            <button
              :class="['type-btn', { active: recommendType === 'picturebook' }]"
              @click="recommendType = 'picturebook'"
            >
              📚 绘本
            </button>
            <button
              :class="['type-btn', { active: recommendType === 'audio' }]"
              @click="recommendType = 'audio'"
            >
              🎵 音频
            </button>
          </div>

          <div class="resource-list">
            <!-- 全选控制 -->
            <div class="select-all-resources" v-if="currentResourceList.length > 0">
              <label class="select-all-label">
                <input
                  type="checkbox"
                  :checked="allResourcesSelected"
                  :indeterminate="someResourcesSelected"
                  @change="toggleAllResources"
                />
                <span>全选</span>
              </label>
            </div>

            <!-- 课件列表 -->
            <div v-if="recommendType === 'courseware'" class="content-list">
              <div class="content-card" v-for="courseware in (coursewares || [])" :key="courseware.id || courseware.fileName">
                <div class="content-header">
                  <h4>{{ courseware.displayName || courseware.name || courseware.originalName || courseware.fileName }}</h4>
                  <span class="content-meta">大小: {{ formatFileSize(courseware.size) }} | 上传时间: {{ formatDate(courseware.uploadTime) }}</span>
                </div>
                <div class="content-actions">
                  <label class="checkbox-label">
                    <input type="checkbox" v-model="courseware.selected" />
                    选择
                  </label>
                </div>
              </div>
              <div v-if="!coursewares || coursewares.length === 0" class="empty-state">
                <p>暂无课件</p>
              </div>
            </div>

            <!-- 绘本列表 -->
            <div v-if="recommendType === 'picturebook'" class="content-list">
              <div class="content-card" v-for="book in (picturebooks || [])" :key="book.id || book.fileName">
                <div class="content-header">
                  <h4>{{ book.displayName || book.name || book.originalName || book.fileName }}</h4>
                  <span class="content-meta">大小: {{ formatFileSize(book.size) }} | 上传时间: {{ formatDate(book.uploadTime) }}</span>
                </div>
                <div class="content-actions">
                  <label class="checkbox-label">
                    <input type="checkbox" v-model="book.selected" />
                    选择
                  </label>
                </div>
              </div>
              <div v-if="!picturebooks || picturebooks.length === 0" class="empty-state">
                <p>暂无绘本</p>
              </div>
            </div>

            <!-- 音频列表 -->
            <div v-if="recommendType === 'audio'" class="content-list">
              <div class="content-card" v-for="audio in (audios || [])" :key="audio.id || audio.fileName">
                <div class="content-header">
                  <h4>{{ audio.displayName || audio.name || audio.originalName || audio.fileName }}</h4>
                  <span class="content-meta">大小: {{ formatFileSize(audio.size) }} | 上传时间: {{ formatDate(audio.uploadTime) }}</span>
                </div>
                <div class="content-actions">
                  <label class="checkbox-label">
                    <input type="checkbox" v-model="audio.selected" />
                    选择
                  </label>
                </div>
              </div>
              <div v-if="!audios || audios.length === 0" class="empty-state">
                <p>暂无音频</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 上传对话框 - 集成大文件上传组件 -->
    <div v-if="showUploadDialog" class="modal-overlay" @click="showUploadDialog = false">
      <div class="modal-content upload-modal" @click.stop>
        <div class="modal-header">
          <h3>上传{{ activeTab === 'courseware' ? '课件' : activeTab === 'picturebook' ? '绘本' : activeTab === 'audio' ? '音频' : '' }}</h3>
          <button class="modal-close" @click="showUploadDialog = false">×</button>
        </div>
        <div class="modal-body">
          <BigFileUpload
            :max-file-size="2048"
            :chunk-size="5"
            :multiple="true"
            :concurrent-uploads="3"
            :file-type="activeTab === 'courseware' ? 'courseware' : (activeTab === 'picturebook' ? 'picturebook' : (activeTab === 'audio' ? 'audio' : null))"
            @upload-completed="handleUploadCompleted"
            @upload-error="handleUploadError"
            @upload-all-completed="handleUploadAllCompleted"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import BigFileUpload from '@/components/BigFileUpload.vue';
import AudioRecorder from '@/components/AudioRecorder.vue';
import CoursewareUploadDialog from '@/components/CoursewareUploadDialog.vue';
import { fileService } from '@/services/fileService';
import { childEnglishApi } from '@/api/childEnglishApi';
import { usePreviewStore } from '@/stores/previewStore';

export default {
  name: 'TeachingContent',
  components: {
    BigFileUpload,
    AudioRecorder,
    CoursewareUploadDialog
  },
  data() {
    return {
      activeTab: 'courseware',
      showBatchPanel: false,
      showUploadDialog: false,
      batchSelectedClass: '',
      selectAll: false,
      recommendType: 'courseware',
      loadingCoursewares: false,
      loadingPicturebooks: false,
      loadingAudios: false,
      loadingClasses: false,
      loadingStudents: false,
      // 每日推荐相关数据
      selectedClasses: [],
      selectedStudents: [],
      recommendationContent: '',
      classes: [],
      students: [],
      audios: [],
      isComposing: false, // 输入法组合状态
      showAudioRecorder: false, // 显示录音对话框
      showCoursewareUpload: false, // 显示课件上传对话框
      showTipDialog: false, // 显示提示对话框
      tipDialogConfig: {
        icon: '⚠️',
        title: '',
        message: '',
        type: 'warning' // warning, info, error
      },
      activeFormats: {
        bold: false,
        italic: false,
        underline: false
      },
      showPreviewModal: false, // 显示预览对话框
      previewContent: '' // 预览内容
    };
  },
  computed: {
    // 根据选中的班级筛选学生
    filteredStudents() {
      if (this.selectedClasses.length === 0) {
        return [];
      }
      return this.students.filter(student => 
        student.classId && this.selectedClasses.includes(student.classId)
      );
    },
    // 班级全选状态
    allClassesSelected() {
      return this.classes.length > 0 && this.selectedClasses.length === this.classes.length;
    },
    someClassesSelected() {
      return this.selectedClasses.length > 0 && this.selectedClasses.length < this.classes.length;
    },
    // 学生全选状态
    allStudentsSelected() {
      return this.filteredStudents.length > 0 && this.selectedStudents.length === this.filteredStudents.length;
    },
    someStudentsSelected() {
      return this.selectedStudents.length > 0 && this.selectedStudents.length < this.filteredStudents.length;
    },
    // 当前资源列表
    currentResourceList() {
      if (this.recommendType === 'courseware') {
        return this.coursewares || [];
      } else if (this.recommendType === 'picturebook') {
        return this.picturebooks || [];
      } else if (this.recommendType === 'audio') {
        return this.audios || [];
      }
      return [];
    },
    // 资源全选状态
    allResourcesSelected() {
      const list = this.currentResourceList;
      return list.length > 0 && list.every(item => item.selected);
    },
    someResourcesSelected() {
      const list = this.currentResourceList;
      const selectedCount = list.filter(item => item.selected).length;
      return selectedCount > 0 && selectedCount < list.length;
    }
  },
  watch: {
    activeTab(newTab) {
      // 切换标签页时重新加载文件列表
      if (newTab === 'courseware') {
        this.loadCoursewares();
      } else if (newTab === 'picturebook') {
        this.loadPicturebooks();
      } else if (newTab === 'audio') {
        this.loadAudios();
      } else if (newTab === 'recommend') {
        // 切换到每日推荐时加载班级和学生列表
        this.loadClasses();
        this.loadStudents();
        this.loadAudios();
        // 初始化富文本编辑器内容
        this.$nextTick(() => {
          if (this.$refs.richEditor && this.recommendationContent) {
            this.$refs.richEditor.innerHTML = this.recommendationContent;
          }
        });
      }
    },
    selectedClasses() {
      // 当班级选择变化时，清空学生选择
      this.selectedStudents = [];
    }
  },
  mounted() {
    // 初始化加载文件列表
    this.loadCoursewares();
    this.loadPicturebooks();
    this.loadAudios();
    
    // 初始化富文本编辑器
    this.$nextTick(() => {
      if (this.$refs.richEditor && this.recommendationContent) {
        this.$refs.richEditor.innerHTML = this.recommendationContent;
      }
    });
  },
  methods: {
    // 加载课件列表
    async loadCoursewares() {
      this.loadingCoursewares = true;
      try {
        console.log('开始加载课件列表，参数: { type: "courseware" }');
        const response = await fileService.getFileList({ type: 'courseware' });
        console.log('课件列表API完整响应:', JSON.stringify(response, null, 2));
        
        // 处理响应数据 - API拦截器返回的是response.data，即后端R对象的JSON
        let fileList = [];
        
        if (response) {
          // 检查是否是标准的R格式响应 {code, message, data}
          if (response.code === 200 && response.data) {
            fileList = Array.isArray(response.data) ? response.data : [];
            console.log('从response.data获取文件列表，数量:', fileList.length);
          } 
          // 如果直接是数组（不应该发生，但兼容处理）
          else if (Array.isArray(response)) {
            fileList = response;
            console.log('响应直接是数组，数量:', fileList.length);
          }
          // 如果data字段存在但不是标准格式
          else if (response.data && Array.isArray(response.data)) {
            fileList = response.data;
            console.log('从response.data（非标准格式）获取文件列表，数量:', fileList.length);
          } else {
            console.warn('无法解析响应数据，响应结构:', response);
          }
        }
        
        console.log('解析后的文件列表:', fileList);
        
        // 再次按类型过滤，确保只显示课件类型的文件
        const filteredList = fileList.filter(file => {
          const fileType = file.type || file.fileType;
          const isCourseware = fileType === 'courseware';
          if (!isCourseware) {
            console.warn('过滤掉非课件文件:', file.fileName || file.name, '类型:', fileType);
          }
          return isCourseware;
        });
        
        this.coursewares = filteredList.map(file => {
          const fileItem = {
            ...file,
            id: file.id || file.fileName,
            // 优先使用 originalName，然后是 name，最后是 fileName
            name: file.originalName || file.name || file.fileName,
            // 保存原始文件名用于显示
            displayName: file.originalName || file.name || file.fileName,
            selected: false,
            downloading: false,
            paused: false,
            completed: false,
            progress: 0
          };
          console.log('处理文件项:', fileItem);
          return fileItem;
        });
        
        console.log('最终课件列表，数量:', this.coursewares.length, '列表:', this.coursewares);
        
        if (this.coursewares.length === 0) {
          console.warn('课件列表为空，可能的原因：1. 没有上传文件 2. 文件类型不匹配 3. 后端筛选逻辑问题');
        }
      } catch (error) {
        console.error('加载课件列表失败:', error);
        console.error('错误详情:', error.response || error.message);
        this.$message?.error('加载课件列表失败: ' + (error.message || '未知错误'));
      } finally {
        this.loadingCoursewares = false;
      }
    },

    // 加载绘本列表
    async loadPicturebooks() {
      this.loadingPicturebooks = true;
      try {
        const response = await fileService.getFileList({ type: 'picturebook' });
        console.log('绘本列表API响应:', response);
        
        // 处理响应数据 - API拦截器已经返回了response.data
        let fileList = [];
        if (response && response.code === 200 && response.data) {
          fileList = response.data;
        } else if (Array.isArray(response)) {
          // 如果直接返回数组
          fileList = response;
        } else if (response && response.data && Array.isArray(response.data)) {
          fileList = response.data;
        }
        
        // 再次按类型过滤，确保只显示绘本类型的文件
        const filteredList = fileList.filter(file => {
          const fileType = file.type || file.fileType;
          const isPicturebook = fileType === 'picturebook';
          if (!isPicturebook) {
            console.warn('过滤掉非绘本文件:', file.fileName || file.name, '类型:', fileType);
          }
          return isPicturebook;
        });
        
        this.picturebooks = filteredList.map(file => ({
          ...file,
          id: file.id || file.fileName,
          // 优先使用 originalName，然后是 name，最后是 fileName
          name: file.originalName || file.name || file.fileName,
          displayName: file.originalName || file.name || file.fileName,
          selected: false,
          downloading: false,
          paused: false,
          completed: false,
          progress: 0
        }));
        
        console.log('处理后的绘本列表:', this.picturebooks);
      } catch (error) {
        console.error('加载绘本列表失败:', error);
        this.$message?.error('加载绘本列表失败: ' + (error.message || '未知错误'));
      } finally {
        this.loadingPicturebooks = false;
      }
    },

    // 上传完成回调
    handleUploadCompleted(fileItem) {
      console.log('文件上传完成:', fileItem);
      console.log('上传完成详情:', {
        name: fileItem.name,
        finalFileName: fileItem.finalFileName,
        status: fileItem.status,
        progress: fileItem.progress,
        completed: fileItem.completed
      });
      
      this.$message?.success(`文件 "${fileItem.name}" 上传成功`);
      
      // 延迟一下再刷新列表，确保后端文件已保存
      setTimeout(() => {
        console.log('开始刷新文件列表，当前标签页:', this.activeTab);
        // 重新加载文件列表
        if (this.activeTab === 'courseware') {
          this.loadCoursewares();
        } else if (this.activeTab === 'picturebook') {
          this.loadPicturebooks();
        } else if (this.activeTab === 'audio') {
          this.loadAudios();
        }
      }, 800); // 增加延迟时间，确保后端处理完成
    },

    // 上传错误回调
    handleUploadError(fileItem, error) {
      console.error('文件上传失败:', error);
      this.$message?.error(`文件 "${fileItem.name}" 上传失败: ${error.message || '未知错误'}`);
    },

    // 所有文件上传完成回调
    handleUploadAllCompleted() {
      console.log('所有文件上传完成，准备刷新列表');
      
      // 关闭上传对话框
      this.showUploadDialog = false;
      
      // 延迟刷新文件列表，确保后端文件已保存
      setTimeout(() => {
        console.log('开始刷新文件列表，当前标签页:', this.activeTab);
        if (this.activeTab === 'courseware') {
          this.loadCoursewares();
        } else if (this.activeTab === 'picturebook') {
          this.loadPicturebooks();
        } else if (this.activeTab === 'audio') {
          this.loadAudios();
        }
      }, 1000);
    },


    goBack() {
      this.$router.push('/');
    },

    toggleSelectAll() {
      const items = this.activeTab === 'courseware' ? (this.coursewares || []) : 
                   this.activeTab === 'picturebook' ? (this.picturebooks || []) :
                   this.activeTab === 'audio' ? (this.audios || []) : [];
      items.forEach(item => {
        item.selected = this.selectAll;
      });
    },

    batchPush() {
      const items = this.activeTab === 'courseware' ? (this.coursewares || []) : 
                   this.activeTab === 'picturebook' ? (this.picturebooks || []) :
                   this.activeTab === 'audio' ? (this.audios || []) : [];
      const selected = items.filter(item => item.selected);
      const className = this.batchSelectedClass ? 
        this.classes.find(c => c.id === this.batchSelectedClass)?.name : '全部班级';
      const typeName = this.activeTab === 'courseware' ? '课件' : 
                      this.activeTab === 'picturebook' ? '绘本' : '音频';
      this.$message?.info(`将向${className}推送${selected.length}个${typeName}`);
    },

    // 下载课件
    async downloadCourseware(courseware) {
      try {
        const fileName = courseware.fileName || courseware.name;
        if (!fileName) {
          this.$message?.error('文件名不存在');
          return;
        }

        // 使用大文件下载服务
        console.log('开始下载课件:', fileName, '原始文件名:', courseware.displayName || courseware.name);
        await fileService.downloadLargeFile(fileName, {
          onProgress: (progress) => {
            courseware.progress = progress;
            courseware.downloading = true;
          },
          onSuccess: (blob) => {
            console.log('下载成功，Blob大小:', blob.size, 'bytes');
            if (!blob || blob.size === 0) {
              console.error('下载的文件为空！');
              this.$message?.error('下载的文件为空，请检查文件是否上传成功');
              courseware.downloading = false;
              return;
            }
            
            // 创建下载链接，使用原始文件名
            const downloadName = courseware.displayName || courseware.name || fileName;
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = downloadName;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);

            courseware.downloading = false;
            courseware.completed = true;
            this.$message?.success(`课件 "${downloadName}" 下载完成`);
          },
          onError: (error) => {
            console.error('下载失败:', error);
            courseware.downloading = false;
            this.$message?.error(`课件 "${fileName}" 下载失败: ${error.message}`);
          }
        });
      } catch (error) {
        console.error('下载课件失败:', error);
        this.$message?.error(`下载课件失败: ${error.message || '未知错误'}`);
      }
    },

    // 预览课件
    previewCourseware(courseware) {
      const fileName = courseware.fileName || courseware.name;
      if (!fileName) {
        this.$message?.error('文件名不存在');
        return;
      }

      const previewStore = usePreviewStore();
      previewStore.openPreview({
        fileName,
        displayName: courseware.displayName || courseware.name || fileName
      });
    },

    // 删除课件
    async deleteCourseware(courseware) {
      const fileName = courseware.fileName || courseware.name;
      if (!fileName) {
        this.$message?.error('文件名不存在');
        return;
      }

      // 检查审核状态，只有待审核状态才能删除
      if (courseware.reviewStatus !== 0 && courseware.reviewStatus !== null && courseware.reviewStatus !== undefined) {
        this.$message?.warning('已审核的文件不能删除');
        return;
      }

      if (confirm(`确定要删除课件 "${fileName}" 吗？`)) {
        try {
          await fileService.deleteFile(fileName);
          this.$message?.success(`课件 "${fileName}" 删除成功`);
          // 重新加载列表
          this.loadCoursewares();
        } catch (error) {
          console.error('删除课件失败:', error);
          this.$message?.error(`删除课件失败: ${error.message || '未知错误'}`);
        }
      }
    },

    // 下载绘本
    async downloadPicturebook(book) {
      try {
        const fileName = book.fileName || book.name;
        if (!fileName) {
          this.$message?.error('文件名不存在');
          return;
        }

        // 使用大文件下载服务
        await fileService.downloadLargeFile(fileName, {
          onProgress: (progress) => {
            book.progress = progress;
            book.downloading = true;
          },
          onSuccess: (blob) => {
            // 创建下载链接，使用原始文件名
            const downloadName = book.displayName || book.name || fileName;
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = downloadName;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);

            book.downloading = false;
            book.completed = true;
            this.$message?.success(`绘本 "${downloadName}" 下载完成`);
          },
          onError: (error) => {
            book.downloading = false;
            const displayName = book.displayName || book.name || fileName;
            this.$message?.error(`绘本 "${displayName}" 下载失败: ${error.message}`);
          }
        });
      } catch (error) {
        console.error('下载绘本失败:', error);
        this.$message?.error(`下载绘本失败: ${error.message || '未知错误'}`);
      }
    },

    // 预览绘本
    previewPicturebook(book) {
      const fileName = book.fileName || book.name;
      if (!fileName) {
        this.$message?.error('文件名不存在');
        return;
      }

      const previewStore = usePreviewStore();
      previewStore.openPreview({
        fileName,
        displayName: book.displayName || book.name || fileName
      });
    },

    // 删除绘本
    async deletePicturebook(book) {
      const fileName = book.fileName || book.name;
      if (!fileName) {
        this.$message?.error('文件名不存在');
        return;
      }

      // 检查审核状态，只有待审核状态才能删除
      if (book.reviewStatus !== 0 && book.reviewStatus !== null && book.reviewStatus !== undefined) {
        this.$message?.warning('已审核的文件不能删除');
        return;
      }

      if (confirm(`确定要删除绘本 "${fileName}" 吗？`)) {
        try {
          await fileService.deleteFile(fileName);
          this.$message?.success(`绘本 "${fileName}" 删除成功`);
          // 重新加载列表
          this.loadPicturebooks();
        } catch (error) {
          console.error('删除绘本失败:', error);
          this.$message?.error(`删除绘本失败: ${error.message || '未知错误'}`);
        }
      }
    },

    // 下载音频
    async downloadAudio(audio) {
      try {
        const fileName = audio.fileName || audio.name;
        if (!fileName) {
          this.$message?.error('文件名不存在');
          return;
        }

        // 使用大文件下载服务
        await fileService.downloadLargeFile(fileName, {
          onProgress: (progress) => {
            audio.progress = progress;
            audio.downloading = true;
          },
          onSuccess: (blob) => {
            // 创建下载链接，使用原始文件名
            const downloadName = audio.displayName || audio.name || fileName;
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = downloadName;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);

            audio.downloading = false;
            audio.completed = true;
            this.$message?.success(`音频 "${downloadName}" 下载完成`);
          },
          onError: (error) => {
            audio.downloading = false;
            const displayName = audio.displayName || audio.name || fileName;
            this.$message?.error(`音频 "${displayName}" 下载失败: ${error.message}`);
          }
        });
      } catch (error) {
        console.error('下载音频失败:', error);
        this.$message?.error(`下载音频失败: ${error.message || '未知错误'}`);
      }
    },

    // 预览音频
    previewAudio(audio) {
      const fileName = audio.fileName || audio.name;
      if (!fileName) {
        this.$message?.error('文件名不存在');
        return;
      }

      const previewStore = usePreviewStore();
      previewStore.openPreview({
        fileName,
        displayName: audio.displayName || audio.name || fileName,
        fileType: 'audio'
      });
    },

    // 删除音频
    async deleteAudio(audio) {
      const fileName = audio.fileName || audio.name;
      if (!fileName) {
        this.$message?.error('文件名不存在');
        return;
      }

      // 检查审核状态，只有待审核状态才能删除
      if (audio.reviewStatus !== 0 && audio.reviewStatus !== null && audio.reviewStatus !== undefined) {
        this.$message?.warning('已审核的文件不能删除');
        return;
      }

      if (confirm(`确定要删除音频 "${fileName}" 吗？`)) {
        try {
          await fileService.deleteFile(fileName);
          this.$message?.success(`音频 "${fileName}" 删除成功`);
          // 重新加载列表
          this.loadAudios();
        } catch (error) {
          console.error('删除音频失败:', error);
          this.$message?.error(`删除音频失败: ${error.message || '未知错误'}`);
        }
      }
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (!bytes || bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },

    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    },

    // 格式化时间（秒数转换为 MM:SS 格式）
    formatTime(seconds) {
      if (!seconds && seconds !== 0) return '00:00';
      const mins = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },

    // 获取审核状态文本
    getReviewStatusText(reviewStatus) {
      if (reviewStatus === null || reviewStatus === undefined || reviewStatus === 0) {
        return '审核中';
      } else if (reviewStatus === 1) {
        return '已通过';
      } else if (reviewStatus === 2) {
        return '已拒绝';
      }
      return '未知';
    },

    // 获取审核状态样式类
    getReviewStatusClass(reviewStatus) {
      if (reviewStatus === null || reviewStatus === undefined || reviewStatus === 0) {
        return 'status-pending';
      } else if (reviewStatus === 1) {
        return 'status-approved';
      } else if (reviewStatus === 2) {
        return 'status-rejected';
      }
      return '';
    },

    // ========== 每日推荐相关方法 ==========
    
    // 加载班级列表
    async loadClasses() {
      if (this.loadingClasses) return;
      this.loadingClasses = true;
      try {
        const response = await childEnglishApi.getClasses();
        if (response && response.code === 200 && response.data && response.data.classes) {
          this.classes = response.data.classes;
        }
      } catch (error) {
        console.error('加载班级列表失败:', error);
        this.$message?.error('加载班级列表失败: ' + (error.message || '未知错误'));
      } finally {
        this.loadingClasses = false;
      }
    },

    // 加载学生列表
    async loadStudents() {
      if (this.loadingStudents) return;
      this.loadingStudents = true;
      try {
        const response = await childEnglishApi.getStudents();
        if (response && response.code === 200 && response.data && response.data.students) {
          this.students = response.data.students;
        }
      } catch (error) {
        console.error('加载学生列表失败:', error);
        this.$message?.error('加载学生列表失败: ' + (error.message || '未知错误'));
      } finally {
        this.loadingStudents = false;
      }
    },

    // 加载音频列表
    async loadAudios() {
      this.loadingAudios = true;
      try {
        console.log('开始加载音频列表，参数: { type: "audio" }');
        const response = await fileService.getFileList({ type: 'audio' });
        console.log('音频列表API完整响应:', JSON.stringify(response, null, 2));
        
        // 处理响应数据 - API拦截器返回的是response.data，即后端R对象的JSON
        let fileList = [];
        
        if (response) {
          // 检查是否是标准的R格式响应 {code, message, data}
          if (response.code === 200 && response.data) {
            fileList = Array.isArray(response.data) ? response.data : [];
            console.log('从response.data获取文件列表，数量:', fileList.length);
          } 
          // 如果直接是数组（不应该发生，但兼容处理）
          else if (Array.isArray(response)) {
            fileList = response;
            console.log('响应直接是数组，数量:', fileList.length);
          }
          // 如果data字段存在但不是标准格式
          else if (response.data && Array.isArray(response.data)) {
            fileList = response.data;
            console.log('从response.data（非标准格式）获取文件列表，数量:', fileList.length);
          } else {
            console.warn('无法解析响应数据，响应结构:', response);
          }
        }
        
        console.log('解析后的文件列表:', fileList);
        
        // 再次按类型过滤，确保只显示音频类型的文件
        const filteredList = fileList.filter(file => {
          const fileType = file.type || file.fileType;
          const isAudio = fileType === 'audio';
          if (!isAudio) {
            console.warn('过滤掉非音频文件:', file.fileName || file.name, '类型:', fileType);
          }
          return isAudio;
        });
        
        this.audios = filteredList.map(file => {
          const fileItem = {
            ...file,
            id: file.id || file.fileName,
            // 优先使用 originalName，然后是 name，最后是 fileName
            name: file.originalName || file.name || file.fileName,
            // 保存原始文件名用于显示
            displayName: file.originalName || file.name || file.fileName,
            selected: false,
            downloading: false,
            paused: false,
            completed: false,
            progress: 0
          };
          console.log('处理音频文件项:', fileItem);
          return fileItem;
        });
        
        console.log('最终音频列表，数量:', this.audios.length, '列表:', this.audios);
        
        if (this.audios.length === 0) {
          console.warn('音频列表为空，可能的原因：1. 没有上传文件 2. 文件类型不匹配 3. 后端筛选逻辑问题');
        }
      } catch (error) {
        console.error('加载音频列表失败:', error);
        console.error('错误详情:', error.response || error.message);
        this.$message?.error('加载音频列表失败: ' + (error.message || '未知错误'));
      } finally {
        this.loadingAudios = false;
      }
    },

    // 切换班级选择
    toggleClass(classId) {
      const index = this.selectedClasses.indexOf(classId);
      if (index > -1) {
        this.selectedClasses.splice(index, 1);
      } else {
        this.selectedClasses.push(classId);
      }
    },

    // 全选/取消全选班级
    toggleAllClasses() {
      if (this.allClassesSelected) {
        // 如果已全选，则取消全选
        this.selectedClasses = [];
      } else {
        // 如果未全选，则全选
        this.selectedClasses = this.classes.map(c => c.id);
      }
    },

    // 切换学生选择
    toggleStudent(studentId) {
      const index = this.selectedStudents.indexOf(studentId);
      if (index > -1) {
        this.selectedStudents.splice(index, 1);
      } else {
        this.selectedStudents.push(studentId);
      }
    },

    // 全选/取消全选学生
    toggleAllStudents() {
      if (this.allStudentsSelected) {
        // 如果已全选，则取消全选
        this.selectedStudents = [];
      } else {
        // 如果未全选，则全选
        this.selectedStudents = this.filteredStudents.map(s => s.id);
      }
    },

    // 全选/取消全选资源
    toggleAllResources() {
      const list = this.currentResourceList;
      const shouldSelectAll = !this.allResourcesSelected;
      
      list.forEach(item => {
        this.$set(item, 'selected', shouldSelectAll);
      });
    },

    // 输入法开始组合
    onCompositionStart() {
      this.isComposing = true;
    },

    // 输入法结束组合
    onCompositionEnd(event) {
      this.isComposing = false;
      // 组合结束后更新内容
      this.$nextTick(() => {
        this.updateRecommendationContent(event);
      });
    },

    // 更新推荐内容
    updateRecommendationContent(event) {
      // 如果正在输入法组合中，不更新内容（避免中间状态）
      if (this.isComposing) {
        return;
      }
      
      const element = event.target;
      if (!element) return;
      
      // 保存HTML内容用于富文本显示
      // 清理可能的输入法残留标记
      let htmlContent = element.innerHTML;
      
      // 移除输入法相关的标记（如果有）
      htmlContent = htmlContent.replace(/<mark[^>]*>.*?<\/mark>/gi, '');
      
      this.recommendationContent = htmlContent;
    },

    // 格式化文本
    formatText(format) {
      const editor = this.$refs.richEditor;
      if (!editor) return;
      
      editor.focus();
      
      // 检查是否有选中的文字
      const selection = window.getSelection();
      const hasSelection = selection && selection.toString().trim().length > 0;
      
      // 如果没有选中文字，选中全部文字
      if (!hasSelection) {
        const range = document.createRange();
        range.selectNodeContents(editor);
        selection.removeAllRanges();
        selection.addRange(range);
      }
      
      // 切换格式状态
      if (format === 'bold') {
        this.activeFormats.bold = !this.activeFormats.bold;
      } else if (format === 'italic') {
        this.activeFormats.italic = !this.activeFormats.italic;
      } else if (format === 'underline') {
        this.activeFormats.underline = !this.activeFormats.underline;
      }
      
      // 执行格式化命令
      document.execCommand(format, false, null);
      
      // 如果没有选中文字，取消选中（避免全部文字被选中）
      if (!hasSelection) {
        selection.removeAllRanges();
        // 将光标移到末尾
        const range = document.createRange();
        range.collapse(false);
        selection.addRange(range);
      }
      
      // 检查当前选中文本的格式状态
      this.$nextTick(() => {
        this.checkFormatState();
      });
    },
    
    // 检查当前选中文本的格式状态
    checkFormatState() {
      const editor = this.$refs.richEditor;
      if (!editor) return;
      
      try {
        // 检查当前格式状态
        this.activeFormats.bold = document.queryCommandState('bold');
        this.activeFormats.italic = document.queryCommandState('italic');
        this.activeFormats.underline = document.queryCommandState('underline');
      } catch (e) {
        // 如果queryCommandState不支持，忽略错误
        console.debug('格式状态检查失败:', e);
      }
    },

    // 插入语音
    insertVoice() {
      if (this.selectedStudents.length === 0) {
        this.showTipDialog = true;
        this.tipDialogConfig = {
          icon: '⚠️',
          title: '请先选择学生',
          message: '您需要先从左侧选择要接收推荐的学生，然后才能插入语音。',
          type: 'warning'
        };
        return;
      }
      this.showAudioRecorder = true;
    },

    // 处理插入的音频
    handleInsertAudio(audioData) {
      // 插入音频到编辑器
      const editor = this.$refs.richEditor;
      if (editor) {
        // 确保URL是完整的
        let audioUrl = audioData.url;
        if (audioUrl && !audioUrl.startsWith('http')) {
          // 如果是相对路径，添加服务器地址
          const baseUrl = childEnglishApi.getCurrentServer();
          if (audioUrl.startsWith('/')) {
            audioUrl = baseUrl + audioUrl;
          } else {
            audioUrl = baseUrl + '/' + audioUrl;
          }
        }
        const audioId = 'audio_' + Date.now();
        const audioHtml = `
          <div class="audio-embed editable-item" data-audio-id="${audioId}" data-audio-url="${audioUrl}" data-audio-duration="${audioData.duration}">
            <div class="audio-content">
              <div class="audio-info">
                <audio controls src="${audioUrl}"></audio>
                <span class="audio-meta">语音指导 (时长: ${this.formatTime(audioData.duration)})</span>
              </div>
            </div>
            <button class="delete-btn" data-action="delete-audio" title="删除语音">×</button>
          </div>
        `;
        // 将音频插入到编辑器末尾（在所有附件之后）
        const range = document.createRange();
        range.selectNodeContents(editor);
        range.collapse(false); // 折叠到末尾
        const selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
        document.execCommand('insertHTML', false, audioHtml);
        this.updateRecommendationContent({ target: editor });
      }
    },

    // 处理编辑器点击事件（用于删除按钮和格式检查）
    handleEditorClickAndCheckFormat(event) {
      // 处理删除按钮点击
      if (event.target.classList.contains('delete-btn')) {
        event.preventDefault();
        event.stopPropagation();
        const item = event.target.closest('.editable-item');
        if (item) {
          // 确认删除
          if (confirm('确定要删除这个' + (item.classList.contains('audio-embed') ? '语音' : '文件') + '吗？')) {
            item.remove();
            // 更新编辑器内容
            if (this.$refs.richEditor) {
              this.updateRecommendationContent({ target: this.$refs.richEditor });
            }
          }
        }
        return;
      }
      
      // 检查格式状态
      this.$nextTick(() => {
        this.checkFormatState();
      });
    },

    // 插入链接
    insertLink() {
      if (this.selectedStudents.length === 0) {
        this.showTipDialog = true;
        this.tipDialogConfig = {
          icon: '⚠️',
          title: '请先选择学生',
          message: '您需要先从左侧选择要接收推荐的学生，然后才能附加课件链接。',
          type: 'warning'
        };
        return;
      }
      this.showCoursewareUpload = true;
    },

    // 处理插入的课件
    handleInsertCourseware(fileData) {
      // 插入课件链接到编辑器
      const editor = this.$refs.richEditor;
      if (editor) {
        // 确保URL是完整的
        let fileUrl = fileData.url;
        if (fileUrl && !fileUrl.startsWith('http')) {
          // 如果是相对路径，添加服务器地址
          const baseUrl = childEnglishApi.getCurrentServer();
          if (fileUrl.startsWith('/')) {
            fileUrl = baseUrl + fileUrl;
          } else {
            fileUrl = baseUrl + '/' + fileUrl;
          }
        }
        const fileId = 'file_' + Date.now();
        const fileHtml = `
          <div class="courseware-link editable-item" data-file-id="${fileId}" data-file-url="${fileUrl}">
            <a href="${fileUrl}" target="_blank" class="file-content">
              <div class="file-info">
                <span class="file-name">${fileData.fileName}</span>
                <span class="file-meta">${this.formatFileSize(fileData.fileSize)}</span>
              </div>
            </a>
            <button class="delete-btn" data-action="delete-file" title="删除文件">×</button>
          </div>
        `;
        // 查找第一个音频附件的位置，将文件插入到音频之前
        // 如果没有音频，则插入到末尾
        const audioEmbeds = editor.querySelectorAll('.audio-embed');
        if (audioEmbeds.length > 0) {
          // 如果有音频，插入到第一个音频之前
          const firstAudio = audioEmbeds[0];
          const range = document.createRange();
          range.setStartBefore(firstAudio);
          range.collapse(true);
          const selection = window.getSelection();
          selection.removeAllRanges();
          selection.addRange(range);
        } else {
          // 如果没有音频，插入到末尾
          const range = document.createRange();
          range.selectNodeContents(editor);
          range.collapse(false);
          const selection = window.getSelection();
          selection.removeAllRanges();
          selection.addRange(range);
        }
        document.execCommand('insertHTML', false, fileHtml);
        this.updateRecommendationContent({ target: editor });
      }
    },

    // 根据文件类型获取图标
    getFileIcon(fileType) {
      if (!fileType) return '📄';
      const type = fileType.toLowerCase();
      if (type.includes('pdf')) return '📕';
      if (type.includes('powerpoint') || type.includes('presentation') || type.includes('ppt')) return '📊';
      if (type.includes('word') || type.includes('document') || type.includes('doc')) return '📝';
      if (type.includes('excel') || type.includes('spreadsheet') || type.includes('xls')) return '📈';
      if (type.includes('image')) return '🖼️';
      if (type.includes('video')) return '🎬';
      if (type.includes('audio')) return '🎵';
      if (type.includes('zip') || type.includes('rar')) return '📦';
      return '📄';
    },

    // 预览推荐
    previewRecommendation() {
      if (!this.recommendationContent || this.recommendationContent.trim() === '') {
        this.$message?.warning('请先输入推荐内容');
        return;
      }
      // 处理预览内容，确保音频和文件链接正确
      this.previewContent = this.processPreviewContent(this.recommendationContent);
      // 显示预览对话框
      this.showPreviewModal = true;
    },
    
    // 处理预览内容
    processPreviewContent(content) {
      // 处理预览内容，确保所有相对URL都转换为绝对URL
      if (!content) return '';
      
      let processedContent = content;
      const baseUrl = childEnglishApi.getCurrentServer();
      
      // 创建一个临时DOM元素来解析HTML
      const tempDiv = document.createElement('div');
      tempDiv.innerHTML = content;
      
      // 处理音频项
      const audioEmbeds = tempDiv.querySelectorAll('.audio-embed');
      audioEmbeds.forEach((audioEmbed) => {
        let audioUrl = audioEmbed.getAttribute('data-audio-url') || '';
        const duration = audioEmbed.getAttribute('data-audio-duration') || '0';
        
        // 转换URL为绝对URL
        if (audioUrl && !audioUrl.startsWith('http')) {
          if (audioUrl.startsWith('/')) {
            audioUrl = baseUrl + audioUrl;
          } else {
            audioUrl = baseUrl + '/' + audioUrl;
          }
          audioEmbed.setAttribute('data-audio-url', audioUrl);
        }
        
        // 更新audio标签的src
        const audioTag = audioEmbed.querySelector('audio');
        if (audioTag && audioUrl) {
          audioTag.src = audioUrl;
        }
        
        // 移除删除按钮（预览模式下不需要）
        const deleteBtn = audioEmbed.querySelector('.delete-btn');
        if (deleteBtn) {
          deleteBtn.remove();
        }
      });
      
      // 处理文件项
      const coursewareLinks = tempDiv.querySelectorAll('.courseware-link');
      coursewareLinks.forEach((coursewareLink) => {
        let fileUrl = coursewareLink.getAttribute('data-file-url') || '';
        
        // 转换URL为绝对URL
        if (fileUrl && !fileUrl.startsWith('http') && !fileUrl.startsWith('#')) {
          if (fileUrl.startsWith('/')) {
            fileUrl = baseUrl + fileUrl;
          } else {
            fileUrl = baseUrl + '/' + fileUrl;
          }
          coursewareLink.setAttribute('data-file-url', fileUrl);
        }
        
        // 更新链接的href
        const linkTag = coursewareLink.querySelector('a.file-content');
        if (linkTag && fileUrl) {
          linkTag.href = fileUrl;
        }
        
        // 移除删除按钮（预览模式下不需要）
        const deleteBtn = coursewareLink.querySelector('.delete-btn');
        if (deleteBtn) {
          deleteBtn.remove();
        }
      });
      
      return tempDiv.innerHTML;
    },

    // 保存推荐
    saveRecommendation() {
      if (this.selectedStudents.length === 0) {
        this.$message?.warning('请先选择学生');
        return;
      }
      if (!this.recommendationContent || this.recommendationContent.trim() === '') {
        this.$message?.warning('请先输入推荐内容');
        return;
      }
      this.$message?.success('推荐内容已保存');
    },

    // 发送推荐（包含推荐内容和选中的资源）
    sendRecommendation() {
      if (this.selectedStudents.length === 0) {
        this.$message?.warning('请先选择学生');
        return;
      }
      if (!this.recommendationContent || this.recommendationContent.trim() === '') {
        this.$message?.warning('请先输入推荐内容');
        return;
      }

      // 收集所有选中的资源（课件、绘本、音频）
      const selectedResources = [];
      
      // 收集选中的课件
      if (this.coursewares && this.coursewares.length > 0) {
        const selectedCoursewares = this.coursewares.filter(item => item.selected);
        selectedCoursewares.forEach(item => {
          selectedResources.push({
            type: 'courseware',
            fileName: item.fileName || item.name,
            displayName: item.displayName || item.originalName || item.name || item.fileName,
            size: item.size,
            uploadTime: item.uploadTime
          });
        });
      }

      // 收集选中的绘本
      if (this.picturebooks && this.picturebooks.length > 0) {
        const selectedPicturebooks = this.picturebooks.filter(item => item.selected);
        selectedPicturebooks.forEach(item => {
          selectedResources.push({
            type: 'picturebook',
            fileName: item.fileName || item.name,
            displayName: item.displayName || item.originalName || item.name || item.fileName,
            size: item.size,
            uploadTime: item.uploadTime
          });
        });
      }

      // 收集选中的音频
      if (this.audios && this.audios.length > 0) {
        const selectedAudios = this.audios.filter(item => item.selected);
        selectedAudios.forEach(item => {
          selectedResources.push({
            type: 'audio',
            fileName: item.fileName || item.name,
            displayName: item.displayName || item.originalName || item.name || item.fileName,
            size: item.size,
            uploadTime: item.uploadTime
          });
        });
      }

      // 构建发送数据
      const recommendationData = {
        studentIds: this.selectedStudents,
        content: this.recommendationContent,
        resources: selectedResources
      };

      console.log('发送推荐数据:', recommendationData);
      
      // 显示成功消息
      let message = `推荐内容已发送给 ${this.selectedStudents.length} 位学生`;
      if (selectedResources.length > 0) {
        message += `，包含 ${selectedResources.length} 个资源`;
      }
      this.$message?.success(message);
      
      // TODO: 这里可以调用后端API发送推荐
      // await childEnglishApi.sendRecommendation(recommendationData);
    }
  }
};
</script>

<style scoped>
.teaching-content {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 30px;
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.back-btn {
  padding: 10px 20px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
}

.back-btn:hover {
  background: #2980b9;
  transform: translateX(-3px);
}

.page-header h1 {
  margin: 0;
  color: #2c3e50;
  font-size: 2em;
}

.tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  background: white;
  padding: 10px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.tab-btn {
  flex: 1;
  padding: 15px 20px;
  background: #f8f9fa;
  border: 2px solid transparent;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  color: #5d6d7e;
  transition: all 0.3s;
}

.tab-btn:hover {
  background: #e9ecef;
}

.tab-btn.active {
  background: #667eea;
  color: white;
  border-color: #667eea;
}

.tab-content {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  min-height: 500px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  flex-wrap: wrap;
  gap: 15px;
}

.section-header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.btn-primary {
  padding: 12px 24px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: all 0.3s;
}

.btn-primary:hover {
  background: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.4);
}

.btn-secondary {
  padding: 12px 24px;
  background: #95a5a6;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
}

.btn-secondary:hover {
  background: #7f8c8d;
}

.btn-danger {
  padding: 8px 16px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.btn-danger:hover {
  background: #c0392b;
}

.batch-panel {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 25px;
  border: 2px solid #e0e0e0;
}

.batch-panel h3 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.batch-controls {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-group label {
  font-weight: bold;
  color: #2c3e50;
}

.class-select {
  padding: 8px 15px;
  border: 2px solid #e0e0e0;
  border-radius: 6px;
  font-size: 14px;
}

.checkbox-group label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-weight: bold;
  color: #2c3e50;
}

.content-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.content-card {
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s;
}

.content-card:hover {
  border-color: #667eea;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.2);
}

.content-header {
  margin-bottom: 15px;
}

.content-header h3 {
  margin: 0 0 10px 0;
  color: #2c3e50;
}

.content-meta {
  color: #7f8c8d;
  font-size: 14px;
}

.content-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  font-size: 14px;
  color: #2c3e50;
}

.recommend-section {
  margin-top: 20px;
}

.recommend-type-selector {
  display: flex;
  gap: 10px;
  margin-bottom: 25px;
}

.type-btn {
  padding: 12px 24px;
  background: #f8f9fa;
  border: 2px solid transparent;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  color: #5d6d7e;
  transition: all 0.3s;
}

.type-btn:hover {
  background: #e9ecef;
}

.type-btn.active {
  background: #667eea;
  color: white;
  border-color: #667eea;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #7f8c8d;
}

.empty-state p {
  font-size: 18px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 30px;
  border-radius: 12px;
  max-width: 500px;
  width: 90%;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
}

.modal-content h3 {
  margin: 0 0 15px 0;
  color: #2c3e50;
}

.modal-content .hint {
  color: #7f8c8d;
  margin-bottom: 20px;
}

.modal-content button {
  margin-right: 10px;
  margin-top: 10px;
}

.upload-modal {
  max-width: 900px;
  width: 95%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #e0e0e0;
  margin-bottom: 20px;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
}

.modal-close {
  background: none;
  border: none;
  font-size: 28px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
}

.modal-close:hover {
  background: #f0f0f0;
  color: #333;
}

.modal-body {
  padding: 0;
}

.loading-state {
  text-align: center;
  padding: 60px 20px;
  color: #7f8c8d;
}

.loading-state p {
  font-size: 18px;
}

/* 审核状态样式 */
.review-status {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  margin-left: 10px;
}

.review-status.status-pending {
  background: #fff3cd;
  color: #856404;
  border: 1px solid #ffc107;
}

.review-status.status-approved {
  background: #d4edda;
  color: #155724;
  border: 1px solid #28a745;
}

.review-status.status-rejected {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #dc3545;
}

.btn-danger:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: #95a5a6;
}

/* ========== 每日推荐布局样式 ========== */
.recommend-layout {
  display: flex;
  gap: 20px;
  height: calc(100vh - 300px);
  min-height: 600px;
}

/* 左侧：班级和学生列表 */
.recommend-sidebar {
  width: 300px;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  overflow-y: auto;
}

.recommend-sidebar h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 18px;
}

.class-selector,
.student-selector {
  margin-bottom: 25px;
}

.selector-label {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 14px;
}

.select-all-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: normal;
  font-size: 13px;
  color: #667eea;
  cursor: pointer;
  margin: 0;
}

.select-all-label input[type="checkbox"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
  flex-shrink: 0;
}

.select-all-resources {
  padding: 10px 0;
  margin-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.select-all-resources .select-all-label {
  font-weight: 500;
  font-size: 14px;
}

.class-list,
.student-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.class-item,
.student-item {
  background: white;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 2px solid transparent;
}

.class-item:hover,
.student-item:hover {
  border-color: #667eea;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

.class-item.active,
.student-item.active {
  border-color: #667eea;
  background: #e8f0fe;
}

.class-checkbox-label,
.student-checkbox-label {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  width: 100%;
  margin: 0;
}

.class-checkbox-label input[type="checkbox"],
.student-checkbox-label input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
  flex-shrink: 0;
}

.class-name {
  font-weight: 500;
  color: #2c3e50;
}

.student-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
}

.student-name {
  font-weight: 500;
  color: #2c3e50;
  font-size: 14px;
}

.student-class {
  font-size: 12px;
  color: #7f8c8d;
}

.empty-hint {
  text-align: center;
  padding: 20px;
  color: #7f8c8d;
  font-size: 14px;
}

/* 中间：推荐内容编辑区 */
.recommend-editor {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-radius: 12px;
  padding: 20px;
}

.editor-header h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 18px;
}

.editor-toolbar {
  display: flex;
  gap: 10px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 15px;
}

.toolbar-btn {
  padding: 8px 16px;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s;
  color: #2c3e50;
}

.toolbar-btn:hover {
  background: #e9ecef;
}

.toolbar-btn.active {
  background: #95a5a6;
  color: white;
  border-color: #95a5a6;
}

.toolbar-btn.active:hover {
  background: #7f8c8d;
  border-color: #7f8c8d;
}

.rich-editor {
  flex: 1;
  min-height: 400px;
  padding: 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  overflow-y: auto;
  outline: none;
  line-height: 1.6;
}

.rich-editor:empty:before {
  content: attr(placeholder);
  color: #7f8c8d;
}

/* 确保编辑器中的内容整齐排列 */
.rich-editor > * {
  margin: 12px 0;
}

.rich-editor > *:first-child {
  margin-top: 0;
}

.rich-editor > *:last-child {
  margin-bottom: 0;
}

/* 编辑器中的文本段落样式 */
.rich-editor p {
  margin: 8px 0;
  line-height: 1.8;
}

.rich-editor p:first-child {
  margin-top: 0;
}

.rich-editor p:last-child {
  margin-bottom: 0;
}

/* 确保音频和文件项目之间有清晰的间距 */
.rich-editor .audio-embed + .audio-embed,
.rich-editor .courseware-link + .courseware-link,
.rich-editor .audio-embed + .courseware-link,
.rich-editor .courseware-link + .audio-embed {
  margin-top: 16px;
}

/* 指导意见和附件之间的间距 */
.rich-editor p + .audio-embed,
.rich-editor p + .courseware-link,
.rich-editor br + .audio-embed,
.rich-editor br + .courseware-link {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e0e0e0;
}

/* 确保第一个附件前有分隔线（如果有文本内容） */
.rich-editor:not(:empty) > .audio-embed:first-of-type,
.rich-editor:not(:empty) > .courseware-link:first-of-type {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e0e0e0;
}

/* 音频嵌入样式 */
.rich-editor .audio-embed {
  display: flex !important;
  align-items: center !important;
  justify-content: flex-start !important;
  margin: 12px 0 !important;
  padding: 12px 15px !important;
  background: #ffffff !important;
  border-radius: 8px !important;
  border: 2px solid #e0e0e0 !important;
  border-left: 4px solid #3498db !important;
  gap: 10px !important;
  min-height: 50px !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08) !important;
  transition: all 0.3s !important;
  position: relative !important;
  flex-wrap: nowrap !important;
  width: 100% !important;
  box-sizing: border-box !important;
}

.rich-editor .audio-embed:hover {
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2) !important;
  border-color: #3498db !important;
  background: #f8fbff !important;
}

.rich-editor .audio-embed .audio-content {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  min-width: 0;
  flex-wrap: nowrap;
  overflow: visible;
  pointer-events: none;
}

.rich-editor .audio-embed .audio-content * {
  pointer-events: auto;
}

.rich-editor .audio-embed .audio-info {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  min-width: 0;
  flex-wrap: nowrap;
  overflow: visible;
}

.rich-editor .audio-embed audio {
  width: auto;
  min-width: 120px;
  max-width: 250px;
  height: 32px;
  flex-shrink: 1;
}

.rich-editor .audio-embed .audio-meta {
  font-size: 12px;
  color: #7f8c8d;
  white-space: nowrap;
  flex-shrink: 0;
}

/* 删除按钮样式 */
.rich-editor .delete-btn {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%) !important;
  color: white !important;
  border: none !important;
  border-radius: 8px !important;
  width: 32px !important;
  height: 32px !important;
  min-width: 32px !important;
  min-height: 32px !important;
  cursor: pointer !important;
  font-size: 18px !important;
  line-height: 1 !important;
  flex-shrink: 0 !important;
  transition: all 0.3s ease !important;
  opacity: 1 !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  font-weight: bold !important;
  padding: 0 !important;
  margin-left: auto !important;
  position: relative !important;
  z-index: 1000 !important;
  box-shadow: 0 2px 6px rgba(231, 76, 60, 0.3) !important;
  pointer-events: auto !important;
  user-select: none !important;
}

.rich-editor .delete-btn:hover {
  background: linear-gradient(135deg, #c0392b 0%, #a93226 100%) !important;
  transform: scale(1.1) translateY(-1px) !important;
  opacity: 1 !important;
  box-shadow: 0 4px 12px rgba(231, 76, 60, 0.5) !important;
}

.rich-editor .delete-btn:active {
  transform: scale(1.05) translateY(0) !important;
  box-shadow: 0 2px 6px rgba(231, 76, 60, 0.4) !important;
}

.rich-editor .editable-item:hover .delete-btn {
  opacity: 1 !important;
}

/* 课件链接样式 */
.rich-editor .courseware-link {
  display: flex !important;
  align-items: center !important;
  justify-content: flex-start !important;
  margin: 12px 0 !important;
  padding: 12px 15px !important;
  background: #ffffff !important;
  border-radius: 8px !important;
  border: 2px solid #e0e0e0 !important;
  border-left: 4px solid #2ecc71 !important;
  gap: 10px !important;
  min-height: 50px !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08) !important;
  transition: all 0.3s !important;
  position: relative !important;
  flex-wrap: nowrap !important;
  width: 100% !important;
  box-sizing: border-box !important;
}

.rich-editor .courseware-link:hover {
  box-shadow: 0 4px 12px rgba(46, 204, 113, 0.2) !important;
  border-color: #2ecc71 !important;
  background: #f8fff9 !important;
}

.rich-editor .courseware-link .file-content {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 0 1 auto;
  min-width: 0;
  text-decoration: none;
  color: #2c3e50;
  flex-wrap: nowrap;
  overflow: visible;
}

.rich-editor .courseware-link .file-icon {
  font-size: 28px;
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e8f8f0;
  border-radius: 8px;
}

.rich-editor .courseware-link .file-info {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 0 1 auto;
  min-width: 0;
  flex-wrap: nowrap;
  overflow: visible;
}

.rich-editor .courseware-link .file-name {
  font-weight: bold;
  font-size: 14px;
  color: #2c3e50;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px;
  flex-shrink: 1;
}

.rich-editor .courseware-link .file-meta {
  font-size: 12px;
  color: #7f8c8d;
  white-space: nowrap;
  flex-shrink: 0;
}

/* 确保删除按钮始终可见 */
.rich-editor .audio-embed .delete-btn,
.rich-editor .courseware-link .delete-btn {
  visibility: visible !important;
  display: flex !important;
  opacity: 1 !important;
  position: relative !important;
  z-index: 100 !important;
}

.editor-footer {
  display: flex;
  gap: 10px;
  margin-top: 15px;
  justify-content: flex-end;
}

/* 提示对话框样式 */
.tip-dialog-overlay {
  z-index: 2000; /* 确保在其他对话框之上 */
}

.tip-dialog {
  max-width: 450px;
  padding: 0;
  overflow: hidden;
  animation: tipDialogSlideIn 0.3s ease-out;
}

@keyframes tipDialogSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.tip-dialog-header {
  display: flex;
  align-items: center;
  padding: 24px 24px 16px 24px;
  border-bottom: 1px solid #e0e0e0;
  gap: 16px;
}

.tip-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  flex-shrink: 0;
}

.tip-icon.warning {
  background: #fff3cd;
  color: #856404;
}

.tip-icon.info {
  background: #d1ecf1;
  color: #0c5460;
}

.tip-icon.error {
  background: #f8d7da;
  color: #721c24;
}

.tip-title {
  flex: 1;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.tip-close-btn {
  background: none;
  border: none;
  font-size: 28px;
  color: #7f8c8d;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s;
  flex-shrink: 0;
}

.tip-close-btn:hover {
  background: #f0f0f0;
  color: #2c3e50;
}

.tip-dialog-body {
  padding: 20px 24px;
}

.tip-message {
  margin: 0;
  font-size: 15px;
  line-height: 1.6;
  color: #5d6d7e;
}

.tip-dialog-footer {
  padding: 16px 24px 24px 24px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #f0f0f0;
}

.tip-confirm-btn {
  padding: 10px 24px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.tip-confirm-btn:hover {
  background: #5568d3;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 右侧：资源列表 */
.recommend-resources {
  width: 350px;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.recommend-resources h3 {
  margin: 0 0 20px 0;
  color: #2c3e50;
  font-size: 18px;
}

.resource-type-selector {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.resource-type-selector .type-btn {
  flex: 1;
  min-width: 80px;
  padding: 10px 16px;
  background: white;
  border: 2px solid transparent;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  color: #5d6d7e;
  transition: all 0.3s;
}

.resource-type-selector .type-btn:hover {
  background: #e9ecef;
}

.resource-type-selector .type-btn.active {
  background: #667eea;
  color: white;
  border-color: #667eea;
}

.resource-list {
  flex: 1;
  overflow-y: auto;
}

.resource-list .content-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.resource-list .content-card {
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  padding: 15px;
  background: white;
  transition: all 0.3s;
}

.resource-list .content-card:hover {
  border-color: #667eea;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}

.resource-list .content-header h4 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 14px;
  font-weight: 600;
}

.resource-list .content-meta {
  color: #7f8c8d;
  font-size: 12px;
}

.resource-list .content-actions {
  margin-top: 10px;
}

.resource-list .empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #7f8c8d;
  font-size: 14px;
}

.batch-push-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
}

.batch-push-section .btn-primary {
  width: 100%;
}

/* 预览对话框样式 */
.preview-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.preview-modal {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.preview-header h3 {
  margin: 0;
  color: #2c3e50;
}

.preview-header .close-btn {
  background: none;
  border: none;
  font-size: 28px;
  color: #7f8c8d;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  line-height: 30px;
  transition: color 0.3s;
}

.preview-header .close-btn:hover {
  color: #e74c3c;
}

.preview-content-wrapper {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.preview-content {
  color: #2c3e50;
  line-height: 1.6;
}

.preview-content p {
  margin: 8px 0;
  line-height: 1.8;
}

.preview-content .audio-embed {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin: 12px 0;
  padding: 10px 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #3498db;
  gap: 10px;
  min-height: 50px;
  flex-wrap: nowrap;
  width: 100%;
}

.preview-content .audio-embed .audio-content {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 0 1 auto;
  min-width: 0;
  flex-wrap: nowrap;
}

.preview-content .audio-embed .audio-icon {
  font-size: 24px;
  flex-shrink: 0;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e8f4fe;
  border-radius: 8px;
}

.preview-content .audio-embed .audio-info {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 0 1 auto;
  min-width: 0;
  flex-wrap: nowrap;
}

.preview-content .audio-embed audio {
  width: auto;
  min-width: 120px;
  max-width: 250px;
  height: 32px;
  flex-shrink: 1;
}

.preview-content .audio-embed .audio-meta {
  font-size: 12px;
  color: #7f8c8d;
  white-space: nowrap;
  flex-shrink: 0;
}

.preview-content .courseware-link {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin: 12px 0;
  padding: 10px 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #2ecc71;
  gap: 10px;
  min-height: 50px;
  flex-wrap: nowrap;
  width: 100%;
}

.preview-content .courseware-link .file-content {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 0 1 auto;
  min-width: 0;
  text-decoration: none;
  color: #2c3e50;
  flex-wrap: nowrap;
}

.preview-content .courseware-link .file-icon {
  font-size: 28px;
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e8f8f0;
  border-radius: 8px;
}

.preview-content .courseware-link .file-info {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 0 1 auto;
  min-width: 0;
  flex-wrap: nowrap;
}

.preview-content .courseware-link .file-name {
  font-weight: bold;
  font-size: 14px;
  color: #2c3e50;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px;
  flex-shrink: 1;
}

.preview-content .courseware-link .file-meta {
  font-size: 12px;
  color: #7f8c8d;
  white-space: nowrap;
  flex-shrink: 0;
}

.preview-footer {
  padding: 20px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: flex-end;
}
</style>

